import java.util.ArrayList;
import java.util.List;

class Solution {
    List<String> ret;
    StringBuilder path;
    int left = 0;
    int right = 0;
    int n = 0;
    public List<String> generateParenthesis(int _n) {
        ret = new ArrayList<>();
        path = new StringBuilder();
        n = _n;

        dfs();
        return ret;
    }
    public void dfs(){
        if(right == n){
            ret.add(path.toString());
            return;
        }
        // 剪枝
        if(left < n){
            path.append('(');
            left++;
            dfs();
            path.deleteCharAt(path.length() - 1);
            left--;
        }
        if(right < left){
            path.append(')');
            right++;
            dfs();
            path.deleteCharAt(path.length() - 1);
            right--;
        }
    }
}